/*
Portions Copyright 2019-2021 ZomboDB, LLC.
Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>

All rights reserved.

Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/

//
// we allow improper_ctypes just to eliminate these warnings:
//      = note: `#[warn(improper_ctypes)]` on by default
//      = note: 128-bit integers don't currently have a known stable ABI
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(improper_ctypes)]
#![allow(clippy::unneeded_field_pattern)]
#![cfg_attr(nightly, feature(strict_provenance))]

#[cfg(
    any(
        // no features at all will cause problems
        not(any(feature = "og3")),
  ))]
std::compile_error!("exactly one feature must be provided (og3)");

pub mod submodules;

use core::ptr::NonNull;
use std::ffi::CStr;
pub use submodules::{guard, *};

//
// our actual bindings modules -- these are generated by build.rs
//

// feature gate each pg version module
#[cfg(all(feature = "og3", not(docsrs)))]
mod og3 {
    include!(concat!(env!("OUT_DIR"), "/og3.rs"));
}
#[cfg(all(feature = "og3", docsrs))]
mod og3;

// export each module publicly
#[cfg(feature = "og3")]
pub use og3::*;

// feature gate each pg-specific oid module
#[cfg(all(feature = "og3", not(docsrs)))]
mod og3_oids {
    include!(concat!(env!("OUT_DIR"), "/og3_oids.rs"));
}
#[cfg(all(feature = "og3", docsrs))]
mod og3_oids;

// export that module publicly
#[cfg(feature = "og3")]
pub use og3_oids::*;

// expose things we want available for all versions
pub use all_versions::*;

// and things that are version-specific
#[cfg(feature = "og3")]
pub use internal::og3::add_bool_reloption;
#[cfg(feature = "og3")]
pub use internal::og3::add_int_reloption;
#[cfg(feature = "og3")]
pub use internal::og3::add_string_reloption;
#[cfg(feature = "og3")]
pub use internal::og3::IndexBuildHeapScan;
#[cfg(feature = "og3")]
pub use internal::og3::*;

/// A trait applied to all openGauss `pg_sys::Node` types and subtypes
pub trait PgNode {
    /// Format this node
    #[inline]
    fn display_node(&self) -> String {
        // SAFETY: The trait is pub but this impl is private, and
        // this is only implemented for things known to be "Nodes"
        unsafe { display_node_impl(NonNull::from(self).cast()) }
    }
}

/// implementation function for `impl Display for $NodeType`
///
/// # Safety
/// Don't use this on anything that doesn't impl PgNode, or the type may be off
#[warn(unsafe_op_in_unsafe_fn)]
pub(crate) unsafe fn display_node_impl(node: NonNull<crate::Node>) -> String {
    // SAFETY: It's fine to call nodeToString with non-null well-typed pointers,
    // and pg_sys::nodeToString() returns data via palloc, which is never null
    // as openGauss will ERROR rather than giving us a null pointer,
    // and openGauss starts and finishes constructing StringInfos by writing '\0'
    unsafe {
        let node_cstr = crate::nodeToString(node.as_ptr().cast());

        let result = match CStr::from_ptr(node_cstr).to_str() {
            Ok(cstr) => cstr.to_string(),
            Err(e) => format!("<ffi error: {:?}>", e),
        };

        crate::pfree(node_cstr.cast());

        result
    }
}

/// A trait for converting a thing into a `char *` that is allocated by openGauss' palloc
pub trait AsPgCStr {
    fn as_pg_cstr(&self) -> *mut std::os::raw::c_char;
}

impl<'a> AsPgCStr for &'a str {
    fn as_pg_cstr(&self) -> *mut std::os::raw::c_char {
        let self_bytes = self.as_bytes();
        let pg_cstr = unsafe { crate::palloc0(self_bytes.len() + 1) as *mut std::os::raw::c_uchar };
        let slice = unsafe { std::slice::from_raw_parts_mut(pg_cstr, self_bytes.len()) };
        slice.copy_from_slice(self_bytes);
        pg_cstr as *mut std::os::raw::c_char
    }
}

impl AsPgCStr for String {
    fn as_pg_cstr(&self) -> *mut std::os::raw::c_char {
        self.as_str().as_pg_cstr()
    }
}

/// item declarations we want to add to all versions
mod all_versions {
    use crate as pg_sys;
    use ogx_macros::*;

    use memoffset::*;
    use std::str::FromStr;

    /// this comes from `postgres_ext.h`
    pub const InvalidOid: super::Oid = 0;
    pub const InvalidOffsetNumber: super::OffsetNumber = 0;
    pub const FirstOffsetNumber: super::OffsetNumber = 1;
    pub const MaxOffsetNumber: super::OffsetNumber =
        (super::BLCKSZ as usize / std::mem::size_of::<super::ItemIdData>()) as super::OffsetNumber;
    pub const InvalidBlockNumber: u32 = 0xFFFF_FFFF as crate::BlockNumber;
    pub const VARHDRSZ: usize = std::mem::size_of::<super::int32>();
    pub const InvalidTransactionId: super::TransactionId = 0 as super::TransactionId;
    pub const InvalidCommandId: super::CommandId = (!(0 as super::CommandId)) as super::CommandId;
    pub const FirstCommandId: super::CommandId = 0 as super::CommandId;
    pub const BootstrapTransactionId: super::TransactionId = 1 as super::TransactionId;
    pub const FrozenTransactionId: super::TransactionId = 2 as super::TransactionId;
    pub const FirstNormalTransactionId: super::TransactionId = 3 as super::TransactionId;
    pub const MaxTransactionId: super::TransactionId = 0xFFFF_FFFF as super::TransactionId;

    #[ogx_macros::og_guard]
    extern "C" {
        pub fn ogx_list_nth(list: *mut super::List, nth: i32) -> *mut std::os::raw::c_void;
        pub fn ogx_list_nth_int(list: *mut super::List, nth: i32) -> i32;
        pub fn ogx_list_nth_oid(list: *mut super::List, nth: i32) -> super::Oid;
        pub fn ogx_list_nth_cell(list: *mut super::List, nth: i32) -> *mut super::ListCell;
        pub fn ogx_GETSTRUCT(tuple: pg_sys::HeapTuple) -> *mut std::os::raw::c_char;
    }

    #[inline]
    pub fn VARHDRSZ_EXTERNAL() -> usize {
        offset_of!(super::varattrib_1b_e, va_data)
    }

    #[inline]
    pub fn VARHDRSZ_SHORT() -> usize {
        offset_of!(super::varattrib_1b, va_data)
    }

    #[inline]
    pub fn get_pg_major_version_string() -> &'static str {
        let mver = std::ffi::CStr::from_bytes_with_nul(super::PG_MAJORVERSION).unwrap();
        mver.to_str().unwrap()
    }

    #[inline]
    pub fn get_pg_major_version_num() -> u16 {
        u16::from_str(super::get_pg_major_version_string()).unwrap()
    }

    #[inline]
    pub fn get_pg_version_string() -> &'static str {
        let ver = std::ffi::CStr::from_bytes_with_nul(super::PG_VERSION_STR).unwrap();
        ver.to_str().unwrap()
    }

    #[inline]
    pub fn get_pg_major_minor_version_string() -> &'static str {
        let mver = std::ffi::CStr::from_bytes_with_nul(super::PG_VERSION).unwrap();
        mver.to_str().unwrap()
    }

    #[inline]
    pub fn TransactionIdIsNormal(xid: super::TransactionId) -> bool {
        xid >= FirstNormalTransactionId
    }

    /// ```c
    ///     #define type_is_array(typid)  (get_element_type(typid) != InvalidOid)
    /// ```
    #[inline]
    pub unsafe fn type_is_array(typoid: super::Oid) -> bool {
        super::get_element_type(typoid) != InvalidOid
    }

    #[inline]
    pub unsafe fn planner_rt_fetch(
        index: super::Index,
        root: *mut super::PlannerInfo,
    ) -> *mut super::RangeTblEntry {
        extern "C" {
            pub fn ogx_planner_rt_fetch(
                index: super::Index,
                root: *mut super::PlannerInfo,
            ) -> *mut super::RangeTblEntry;
        }

        ogx_planner_rt_fetch(index, root)
    }

    /// ```c
    /// #define rt_fetch(rangetable_index, rangetable) \
    ///     ((RangeTblEntry *) list_nth(rangetable, (rangetable_index)-1))
    /// ```
    #[inline]
    pub unsafe fn rt_fetch(
        index: super::Index,
        range_table: *mut super::List,
    ) -> *mut super::RangeTblEntry {
        ogx_list_nth(range_table, index as i32 - 1) as *mut super::RangeTblEntry
    }

    #[inline]
    pub fn HeapTupleHeaderGetXmin(
        htup_header: super::HeapTupleHeader,
    ) -> Option<super::TransactionId> {
        extern "C" {
            pub fn ogx_HeapTupleHeaderGetXmin(
                htup_header: super::HeapTupleHeader,
            ) -> super::TransactionId;
        }

        if htup_header.is_null() {
            None
        } else {
            Some(unsafe { ogx_HeapTupleHeaderGetXmin(htup_header) })
        }
    }

    #[inline]
    pub fn HeapTupleHeaderGetRawCommandId(
        htup_header: super::HeapTupleHeader,
    ) -> Option<super::CommandId> {
        extern "C" {
            pub fn ogx_HeapTupleHeaderGetRawCommandId(
                htup_header: super::HeapTupleHeader,
            ) -> super::CommandId;
        }

        if htup_header.is_null() {
            None
        } else {
            Some(unsafe { ogx_HeapTupleHeaderGetRawCommandId(htup_header) })
        }
    }

    /// #define HeapTupleHeaderIsHeapOnly(tup) \
    ///    ( \
    ///       ((tup)->t_infomask2 & HEAP_ONLY_TUPLE) != 0 \
    ///    )
    #[inline]
    pub unsafe fn HeapTupleHeaderIsHeapOnly(htup_header: super::HeapTupleHeader) -> bool {
        ((*htup_header).t_infomask2 & crate::HEAP_ONLY_TUPLE as u16) != 0
    }

    /// #define HeapTupleHeaderIsHotUpdated(tup) \
    /// ( \
    ///      ((tup)->t_infomask2 & HEAP_HOT_UPDATED) != 0 && \
    ///      ((tup)->t_infomask & HEAP_XMAX_INVALID) == 0 && \
    ///      !HeapTupleHeaderXminInvalid(tup) \
    /// )
    #[inline]
    pub unsafe fn HeapTupleHeaderIsHotUpdated(htup_header: super::HeapTupleHeader) -> bool {
        (*htup_header).t_infomask2 & crate::HEAP_HOT_UPDATED as u16 != 0
            && (*htup_header).t_infomask & crate::HEAP_XMAX_INVALID as u16 == 0
            && !HeapTupleHeaderXminInvalid(htup_header)
    }

    /// #define HeapTupleHeaderXminInvalid(tup) \
    /// ( \
    ///   ((tup)->t_infomask & (HEAP_XMIN_COMMITTED|HEAP_XMIN_INVALID)) == \
    ///      HEAP_XMIN_INVALID \
    /// )
    #[inline]
    pub unsafe fn HeapTupleHeaderXminInvalid(htup_header: super::HeapTupleHeader) -> bool {
        (*htup_header).t_infomask
            & (crate::HEAP_XMIN_COMMITTED as u16 | crate::HEAP_XMIN_INVALID as u16)
            == crate::HEAP_XMIN_INVALID as u16
    }

    /// #define BufferGetPage(buffer) ((Page)BufferGetBlock(buffer))
    #[inline]
    pub unsafe fn BufferGetPage(buffer: crate::Buffer) -> crate::Page {
        BufferGetBlock(buffer) as crate::Page
    }

    /// #define BufferGetBlock(buffer) \
    /// ( \
    ///      AssertMacro(BufferIsValid(buffer)), \
    ///      BufferIsLocal(buffer) ? \
    ///            LocalBufferBlockPointers[-(buffer) - 1] \
    ///      : \
    ///            (Block) (BufferBlocks + ((Size) ((buffer) - 1)) * BLCKSZ) \
    /// )
    #[inline]
    pub unsafe fn BufferGetBlock(buffer: crate::Buffer) -> crate::Block {
        if BufferIsLocal(buffer) {
            *crate::LocalBufferBlockPointers.offset(((-buffer) - 1) as isize)
        } else {
            crate::BufferBlocks
                .offset((((buffer as crate::Size) - 1) * crate::BLCKSZ as usize) as isize)
                as crate::Block
        }
    }

    /// #define BufferIsLocal(buffer)      ((buffer) < 0)
    #[inline]
    pub unsafe fn BufferIsLocal(buffer: crate::Buffer) -> bool {
        buffer < 0
    }

    #[inline]
    pub fn heap_tuple_get_struct<T>(htup: super::HeapTuple) -> *mut T {
        if htup.is_null() {
            0 as *mut T
        } else {
            unsafe { ogx_GETSTRUCT(htup) as *mut T }
        }
    }

    #[og_guard]
    extern "C" {
        pub fn query_tree_walker(
            query: *mut super::Query,
            walker: ::std::option::Option<
                unsafe extern "C" fn(*mut super::Node, *mut ::std::os::raw::c_void) -> bool,
            >,
            context: *mut ::std::os::raw::c_void,
            flags: ::std::os::raw::c_int,
        ) -> bool;
    }

    #[og_guard]
    extern "C" {
        pub fn expression_tree_walker(
            node: *mut super::Node,
            walker: ::std::option::Option<
                unsafe extern "C" fn(*mut super::Node, *mut ::std::os::raw::c_void) -> bool,
            >,
            context: *mut ::std::os::raw::c_void,
        ) -> bool;
    }

    #[ogx_macros::og_guard]
    extern "C" {
        fn ogx_SpinLockInit(lock: *mut pg_sys::slock_t);
        fn ogx_SpinLockAcquire(lock: *mut pg_sys::slock_t);
        fn ogx_SpinLockRelease(lock: *mut pg_sys::slock_t);
        fn ogx_SpinLockFree(lock: *mut pg_sys::slock_t) -> bool;
    }

    pub use {
        ogx_SpinLockAcquire as SpinLockAcquire, ogx_SpinLockFree as SpinLockFree,
        ogx_SpinLockInit as SpinLockInit, ogx_SpinLockRelease as SpinLockRelease,
    };
}

mod internal {
    //
    // for specific versions
    //

    #[cfg(feature = "og3")]
    pub(crate) mod og3 {
        use crate::og3::*;

        pub use crate::og3::{
            tupleDesc as TupleDescData, AllocSetContextCreate as AllocSetContextCreateExtended,
        };
        pub type QueryCompletion = std::os::raw::c_char;

        pub unsafe fn add_string_reloption(
            kinds: bits32,
            name: *const ::std::os::raw::c_char,
            desc: *const ::std::os::raw::c_char,
            default_val: *const ::std::os::raw::c_char,
            validator: ::std::option::Option<
                unsafe extern "C" fn(value: *const ::std::os::raw::c_char),
            >,
        ) {
            // og3 defines the validator function as taking a "*mut c_char"
            //
            // For ease of use by users of this crate, we cast the provided
            // 'validator' function to what og3 wants, using transmute
            //
            // If there's a better way to do this, I'ld love to know!
            let func_as_mut_arg = match validator {
                Some(func) => {
                    let func_ptr = std::mem::transmute::<
                        unsafe extern "C" fn(*const ::std::os::raw::c_char),
                        unsafe extern "C" fn(*mut ::std::os::raw::c_char),
                    >(func);
                    Some(func_ptr)
                }
                None => None,
            };

            crate::og3::add_string_reloption(
                kinds,
                name as *mut std::os::raw::c_char,
                desc as *mut std::os::raw::c_char,
                default_val as *mut std::os::raw::c_char,
                func_as_mut_arg,
            );
        }

        pub unsafe fn add_int_reloption(
            kinds: bits32,
            name: *const ::std::os::raw::c_char,
            desc: *const ::std::os::raw::c_char,
            default_val: ::std::os::raw::c_int,
            min_val: ::std::os::raw::c_int,
            max_val: ::std::os::raw::c_int,
        ) {
            crate::og3::add_int_reloption(
                kinds,
                name as *mut std::os::raw::c_char,
                desc as *mut std::os::raw::c_char,
                default_val,
                min_val,
                max_val,
            );
        }

        pub unsafe fn add_bool_reloption(
            kinds: bits32,
            name: *const ::std::os::raw::c_char,
            desc: *const ::std::os::raw::c_char,
            default_val: bool,
        ) {
            crate::og3::add_bool_reloption(
                kinds,
                name as *mut std::os::raw::c_char,
                desc as *mut std::os::raw::c_char,
                default_val,
            );
        }

        /// # Safety
        ///
        /// This function wraps Postgres' internal `IndexBuildHeapScan` method, and therefore, is
        /// inherently unsafe
        pub unsafe fn IndexBuildHeapScan<T>(
            heap_relation: crate::Relation,
            index_relation: crate::Relation,
            index_info: *mut crate::og3::IndexInfo,
            build_callback: crate::IndexBuildCallback,
            build_callback_state: *mut T,
        ) {
            crate::og3::IndexBuildHeapScan(
                heap_relation,
                index_relation,
                index_info,
                true,
                build_callback,
                build_callback_state as *mut std::os::raw::c_void,
            );
        }
    }
}
